﻿using ProgrammersCalculator.Command;
using ProgrammersCalculator.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace ProgrammersCalculator.ViewModel
{
    public class UrlShortnerViewMode : INotifyPropertyChanged
    {
        private static string GoogleResponse(string p)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"longUrl\":\"" + p + "\"}";
                Console.WriteLine(json);
                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var responseText = streamReader.ReadToEnd();
                var result = Newtonsoft.Json.JsonConvert.DeserializeObject<UrlShortner>(responseText);
                return result.ID;
            }
        }

        private string _url;

        private string _shortUrl;

        public string ShortUrl
        {
            get { return _shortUrl; }
            set
            {
                _shortUrl = value;
                RaiseChanged("ShortUrl");
            }
        }
        public string Id
        {
            get { return _url; }
            set
            {
                _url = value;
                UpdateConvertedName(_url);
            }
        }

        private void UpdateConvertedName(string id)
        {

            ShortUrl = GoogleResponse(id);

        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaiseChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}
